layui.config({ //配置全局扩展组件
	base: 'sliderVerify/' //路径一定要对是模块的目录
}).use(['layer', 'element', 'form', 'sliderVerify', 'jquery'], function() {
	var layer = layui.layer,
		element = layui.element,
		form = layui.form,
		$ = layui.jquery,
		sliderVerify = layui.sliderVerify; //引入模块
	//绑定滑块id
	var slider = sliderVerify.render({
		elem: '#slider'
	})

	//判断set是否存在执行自动登录
	if (localStorage.set != null) {
		if (localStorage.set == 'on') {
			var loading = layer.load(1, {
				shade: [0.5, '#bcbcbc'] //0.1透明度的白色背景
			});
			$.ajax({
				url: "http://localhost:8080/sc/admin?type=login",
				async: true, //异步
				type: "POST",
				headers: {
					"token": localStorage.token
				},
				success: function(data) {
					//关闭加载窗口
					layer.close(loading);
					if (data.code == 'TokenFailed') {
						//删除token set
						delete localStorage.token;
						delete localStorage.set;
						layer.msg('登录失效！请重新登录');
					} else {
						//跳转页面
						layer.msg('自动登录成功');
						setTimeout(function() {
							window.location.replace('admin.html');
						}, 1000);
					}
				}
			});
		}
	}

	//执行删除服务器token
	if (localStorage.set != null) {
		if (localStorage.set == '') {
			$.ajax({
				url: "http://localhost:8080/sc/admin?type=del",
				async: true, //异步
				type: "POST",
				headers: {
					"token": localStorage.token
				},
				success: function(data) {
					console.log(data.msg)
				}
			});
		}
	}

	//表单监听
	form.on('submit(login)', function(data) {
		//layer.msg(JSON.stringify(data.field));
		var loading = layer.load(1, {
			shade: [0.5, '#bcbcbc'] //0.1透明度的白色背景
		});
		$.ajax({
			url: "http://localhost:8080/sc/admin?type=login",
			async: true, //异步
			type: "POST",
			data: data.field, //拿到表单数据
			success: function(data) {
				setTimeout(function() {
					layer.close(loading);
					if (data.code == 'LoginError') {
						layer.msg('账号或密码错误！');
					} else {
						//将后端传过来的token保存在localStorage;
						localStorage.token = data.msg;
						//拿到返回过来的记住密码状态
						localStorage.set = data.set;
						layer.msg('登录成功');
						//跳转页面
						setTimeout(function() {
							window.location.replace('admin.html');
						}, 1000);
					}
				}, 2000);
			}
		})
		return false; //一定要有这个玩意儿不然不会执行ajax
	});
})
